/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {Form, Input, Radio, Select, Checkbox, TreeSelect, Button, message, Modal, Drawer} from 'antd';
import {connect} from 'dva';
import request from '@/utils/request';
import {renderSignalIntensity, renderTreeNodes, renderValveOpen} from '@/utils/utils';
import ReactDataGrid from "react-data-grid";
import Loading from "@/components/Loading";
import find from "lodash/find";
import MyPagination from "@/components/MyPagination";
import BuildModalTitle from "@/components/BuildModalTitle";
import JoinAlarm from "./JoinAlarm";
import Detail from "@/pages/Meters/Detail";

const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const Option = Select.Option;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data:[],
      editRecord:{},
      meta: {total: 0, per_page: 30,current_page:1},
      searchParams:{
        number:'',
        user_number:'',
        communication_type:'',
        status:'1',
        caliber:'',
        address:'',
        imei:'',
        page: 1,
        per_page: 50,
      },
      all_vendors: [],
      selectedRowKeys: [],
      loading:false
    };
  }

  componentDidMount() {
    this.handleSearch(this.state.searchParams);
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });

  }
  handleSearch=(values)=>{
    const that=this
    this.setState({
      loading:true
    })
    request(`/meters`, {
      method: 'GET',
      params:{
        ...values,
        // consumption_abnormality_enable:1
      }
    }).then((response)=> {
      if(response.status===200){
        that.setState({
          data: response.data.data,
          meta:response.data.meta,
          loading:false,
          searchParams:values
        })
      }
    })
  }
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const searchParams =this.state.searchParams;
    const username=sessionStorage.getItem('username')
    return (
      <Form layout="inline" className="search-form" style={{marginBottom:'10px'}}>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '120px' }} allowClear disabled={Boolean(username==='宁波水表'||username==='竞达水表'||username==='西安旌旗'||username==='泰安水表'||username==='泰安新贝水表')}>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  handleFormReset = () => {
    const { form } = this.props;
    const username=sessionStorage.getItem('username')
    form.resetFields();
    this.handleSearch({
      number: '',
      user_number: '',
      caliber:'',
      address: '',
      communication_type:'',
      status:'1',
      page: 1,
      per_page: 50,
    });
  };
  handleAddDMA=(item)=>{
    const that=this
    const formValues = this.JoinAlarmFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/meters/${this.state.editRecord.id}/consumption_abnormality_value`, {
      method: 'PUT',
      data: {
        consumption_abnormality_enable:1,
        ...formValues
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success('设置报警成功')
        that.setState({
          editDMAModal:false
        })
        const {
          searchParams
        } = that.state;
        that.handleSearch(searchParams);
        that.props.handleSearch()
      }
    });
  }
  render() {
    const {data,loading,selectedRowKeys,searchParams,meta}=this.state
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const { meta }= this.state;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表号',
        width: 120,
        frozen:true,
        key: 'number',

      },
      {
        name: '安装地址',
        frozen:true,
        key: 'address',
        width: 160  ,
      },
      {
        name: '是否报警',
        key: 'join_area',
        frozen:true,
        width: 140,
        formatter: (event) => {
          return event.row.consumption_abnormality_enable===1?<p className="table-error  table-status">报警</p>:<p className="table-success table-status">不报警</p>

        },
      },
      {
        name: '报警值',
        key: 'consumption_abnormality_value',
        width: 100  ,
      },
      {
        name: '水表厂商名称',
        key: 'vendor_name',
        width: 130,
      },
      {
        name: '协议名称',
        key: 'protocol_name',
        width: 150,
      },
      {
        name: '操作',
        width: 260,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            event.row.consumption_abnormality_enable===-1?
              <Button
                type="primary"
                icon="plus"
                size="small"
                onClick={(e) => {
                  this.setState({
                    status:1,
                    editRecord: event.row,
                    editDMAModal: true,
                  });
                }
                }
              >加入报警
              </Button>:
              <Button
                type="danger"
                icon="delete"
                size="small"
                onClick={(e) => {
                  const that=this
                  request(`/meters/${event.row.id}/consumption_abnormality_value`, {
                    method: 'PUT',
                    data: {
                      consumption_abnormality_enable:-1,
                    },
                  }).then((response) => {
                    if (response.status === 200) {
                      message.success('取消报警成功')
                      that.setState({
                        editDMAModal:false
                      })
                      const {
                        searchParams
                      } = that.state;
                      that.handleSearch(searchParams);
                      that.props.handleSearch()
                    }
                  });
                }
                }
              >取消报警
              </Button>
          }




        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    return (
      <div>
        <div>{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={600}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (index,row) => {
                if (!row) {
                  return;
                }
                this.setState({
                  selectedRowKeys:[index]
                })
              }
            }

          />
          {
            loading && <Loading/>
          }
          <div className="custom-card">
            <div className="table-pagination">
              <MyPagination searchCondition={{ ...searchParams }}
                            resetScrollY={() => {
                            }}
                            meta={meta} handleSearch={this.handleSearch}/>
            </div>
          </div>

        </div>
        <Modal
          title={<BuildModalTitle visible={this.state.editDMAModal} modalClass="editDMAModal"
                                  title={`水表 ${this.state.editRecord.number} 设置报警`}/>}
          visible={this.state.editDMAModal}
          destroyOnClose
          centered
          onOk={this.handleAddDMA}
          className="editDMAModal"
          onCancel={() => {
            this.setState({ editDMAModal: false });
          }}

        >
          <JoinAlarm type={"meter"} editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.JoinAlarmFormRef = inst}/>
        </Modal>
        <Drawer
          title={`${this.state.editRecord.number} 详情`}
          placement="right"
          destroyOnClose
          onClose={() => {
            this.setState({
              infoModal: false,
              editRecord: {},
            });
          }}

          width={700}
          visible={this.state.infoModal}
        >
          <Detail id={this.state.editRecord.id}></Detail>
        </Drawer>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


